#include "usermanager.h"

#include "../Debug/DEBUG.hpp"

UserManager::UserManager() {}

bool UserManager::isExist(uint64_t ID)
{
    std::unique_lock<std::mutex> lockguard(lock);
    if (userStore.count(ID)) {
        return true;
    }
    return false;
}

bool UserManager::isExist(const std::string &account)
{
    std::unique_lock<std::mutex> lockguard(lock);
    if (account_ID.count(account)) {
        return true;
    }
    return false;
}

User &UserManager::createNewUser(uint64_t ID, const std::string &account)
{
    std::unique_lock<std::mutex> lockguard(lock);
    nlohmann::json user;
    user["UserID"] = ID;
    user["Account"] = account;
    userStore[ID] = user;

    account_ID[account] = ID;
    DEBUG_INFO("insert: "+ account +" " +std::to_string(ID));
    return userStore[ID];
}

User& UserManager::getTargetUser(uint64_t ID)
{
    std::unique_lock<std::mutex> lockguard(lock);
    return userStore[ID];
}

User &UserManager::getTargetUser(const std::string &account)
{
    std::unique_lock<std::mutex> lockguard(lock);
    return userStore[account_ID[account]];
}

uint64_t UserManager::account2ID(const std::string &account)
{
    std::unique_lock<std::mutex> lockguard(lock);
    return account_ID[account];
}

void UserManager::deleteTargetUser(uint64_t ID)
{
    std::unique_lock<std::mutex> lockguard(lock);
    account_ID.erase(userStore[ID]["Account"]);
    userStore.erase(ID);
}

bool UserManager::queryUserOnline(uint64_t ID)
{
    std::unique_lock<std::mutex> lockguard(lock);
    if (userStore.count(ID))
        return true;
    return false;
}

bool UserManager::queryUserOnline(const std::string &account)
{
    std::unique_lock<std::mutex> lockguard(lock);
    if (account_ID.count(account))
        return true;
    return false;
}
